<?php
define( 'DS' , DIRECTORY_SEPARATOR );
define( 'APP_ROOT' , dirname( dirname( __FILE__ ) ) . DS  );

// date_default_timezone_set("Asia/Shanghai");
$action = empty( $_REQUEST['ajax'] ) ? '' : strtolower( $_REQUEST['ajax'] );
if($action){
	if($action=='js'){
		$ContentType ='application/x-javascript';
	}else{
		$ContentType ='text/plain';
	}
}else{
	$ContentType ='text/html';
}
header("Content-Type:".$ContentType.";charset=utf-8");

define( 'KIS_APP_ROOT' , dirname( APP_ROOT ) . DS );
include_once KIS_APP_ROOT.'ext_lib'. DS.'comm.function.php';
// include_once KIS_APP_ROOT.'lib'. DS.'app.function.php';
define( 'AROOT' , KIS_APP_ROOT);
define( 'CROOT' , KIS_APP_ROOT.'_lp'. DS.'core'. DS  );
include_once CROOT. 'lib'.DS.'core.function.php';
include_once( KIS_APP_ROOT. 'ext_lib'.DS .'mail.config.inc.php' );

include_once 'php/kisRandomMap.php';
include_once 'php/kisAStar.php';
include_once 'php/kisBSP.class.php';
include_once 'php/map.inc.php';
include_once 'php/func.inc.php';

define('APP_ENVIRONMENT', 'DEVELOPMENT');
// define('APP_ENVIRONMENT', 'PRODUCT');
// define('KIS_DEBUG_MODE', 'DISABLE_DEBUG');

/**

*/


function gen_new_dungeon()   //地牢
{
    return generation_new_random_map(2);
}

function gen_new_outskirts()   //郊区
{
    return generation_new_random_map(1);
}


function generation_new_random_map($map_type=1)
{
    global $ksRndMap, $aStar, $w ,$h, $density, $tmpNodeSet, $grids, $baseNodeSet , $path, $roadpath;
    global $debugMode, $time_log;

    $max = 1000;
    $tt = intval(v('w'))  ;
    if ($tt>0 && $tt<=$max){
        $w=$tt;
    }else{
        die('403 Access Denied/Forbidden');
    }

    $tt = intval(v('h'))  ;
    if ($tt>0 && $tt<=$max){
        $h=$tt;
    }else{
        die('403 Access Denied/Forbidden');
    }

    //初始化数据库
    init_db_random_map_info();

    $tt = intval(v('d'))  ;
    if ($tt>0 && $tt<100){
        $density=$tt;
    }

    $ksRndMap = new kisRandomMap();
    $aStar = new AStar();

    $endId = ($w * $h)-1;

    // $time_log.= "基础加载时间: ". used_time($pagestartime) ."秒.<br/>".PHP_EOL; 
    $time1=microtime(); 

    $ksRndMap->set($w, $h);
    // if($debugMode) $ksRndMap->set_debug(1);

    if($map_type===2){
        /**
        + ------------------------------------------------------------------
        +     地牢模式
        + ------------------------------------------------------------------
        */

        $ksRndMap->setDensity(0);
        $ksRndMap->create();
        $grids = $ksRndMap->get();
        // var_dump($grids);

        $ksLeaf = new ksLeaf(0,0,$w,$h);     
        // $color_config = array('leaf'=>'1','room'=>'5','hall'=>'5','base'=>'0');
        $color_config = array('leaf'=>'5','room'=>'1','hall'=>'1','base'=>'5');
        $color_config['sort'] = 'hall;room;leaf;base';
        $ksLeaf->set_color_config($color_config);

        $bsp = new ksBSP();

        $_leafs = $bsp->BSP($ksLeaf);
        // var_dump($_leafs);
        // echo print_r($_leafs,true);

        // next, iterate through each Leaf and create a room in each one.
        $ksLeaf->createRooms();

        $map = array();
        $map['w'] = +$w;
        $map['h'] = +$h;
        $map['grids'] = $grids;
        $ksLeaf->fillMaps($map,1);

        // echo print_r($_leafs,true);

        $grids = $map['grids'];
        // echo PHP_EOL.'## grids ## '.PHP_EOL;
        // echo print_r($grids,true);

        $grids = convert_map_grids($grids,+$w,+$h,$color_config);

        $ksRndMap->set_grids($grids);

        // var_dump($ksLeaf);
        // var_dump($map);
        // echo PHP_EOL.'## ksLeaf ## '.PHP_EOL;
        // echo print_r($ksLeaf,true);

        // die('DEBUG END!');

        $tmpNodeSet=array();
        $baseNodeSet=array();                                

        $time_log.= "map->create 时间: ". used_time($time1) ."秒.<br/>".PHP_EOL; 
        // $time2=microtime(); 

        $path=array();
        $roadpath=array();
        if($baseNodeSet && is_array($baseNodeSet)){
          foreach ($baseNodeSet as $value) {
            array_push($path,$value);
          }  
        }

        $newPath = array();
        foreach ($grids as $key => $value) {
          if($value){
            if(!isset($newPath[$value])){
              $newPath[$value]=array();
            }
            array_push($newPath[$value], $key);
          }
        }
        // var_dump($newPath);

        $path = $newPath;
        // echo PHP_EOL.'## path ## '.PHP_EOL;
        // echo print_r($path,true);


    }else if($map_type===1){
        /**
        + ------------------------------------------------------------------
        +     随机地图（村庄及其周边）模式
        + ------------------------------------------------------------------
        */

        $ksRndMap->create();
        $ksRndMap->setDensity($density);
        $ksRndMap->run_ca();

        $tmpNodeSet=$ksRndMap->debug_walk();
        $grids = $ksRndMap->get();
        $baseNodeSet=$ksRndMap->debug_nodeSet();
        $time_log.= "map->create 时间: ". used_time($time1) ."秒.<br/>".PHP_EOL; 
        $time2=microtime(); 

        // $path=$tmpNodeSet;
        $path=array();
        $roadpath=array();
        foreach ($baseNodeSet as $value) {
            array_push($path,$value);
        }

        // 寻路
        $aStar->set($w, $h, $grids);
        // $path = $aStar->search(0, $endId);       // 从零开始找到35
        $roadArr=$ksRndMap->get_road();
        // var_dump($roadArr);
        foreach ($roadArr as $road) {
            $roadInfo=$ksRndMap->getRoadByNodeSet($road['from'],$road['to'],$baseNodeSet);
            $pos1 = $roadInfo['from'];
            $pos2 = $roadInfo['to'];
            $tmpPath=array();
            $tmpPath = $aStar->search($pos1, $pos2);
            // if($debugMode) {
            //     echo '--path array,#'.$pos1.'-#'.$pos2.':'.implode(',',$tmpPath) .PHP_EOL.PHP_EOL.PHP_EOL; 
            // }
            $tmpPath2=array();
            array_push($tmpPath2,'road_'.$pos1.'_'.$pos2);
            foreach ($tmpPath as $roadPos) {
                if($roadPos!==$pos1 && $roadPos!==$pos2){
                    array_push($tmpPath2,$roadPos);
                }
            }
            $tmpPath2 = fix_roadPath($tmpPath2);
            array_push($roadpath,$tmpPath2);    
        }
        //array_push($path,$roadpath);
        // var_dump($roadpath);
        $time_log.= "aStar->search 时间: ". used_time($time2) ."秒.<br/>".PHP_EOL; 
    
    }else{
        die('403 Access Denied/Forbidden');
    }

    $mapJson = array();
    $mapJson['map'] = $ksRndMap->getMapJsonObj();
    $mapJson['road'] = $roadpath;
    $mapJson['path'] = $path;

    return $mapJson;
}

/**






*/


$pagestartime=microtime(); 
$time_log='';

$c='default';
$a='newmap';
$html_tpl='';

$tt = v('c') ;  if($tt) $c=$tt;
$tt = v('a') ;  if($tt) $a=$tt;

if(strlen($c)>=3 && strlen($a)>=3){
    //base check
}else{
    die('403 Access Denied/Forbidden');
}

$cgi = '';
$w = 6;     // 宽
$h = 6;     // 高
$density = 55;    // 密度
$debugMode = 0;

$tt = intval(v('debug'))  ;
if ($tt>0 ){
    $debugMode=1;
    $cgi .= '&debug=1';    
}

$map_uuid = null;
$map_type = null;
$grids = null;
$limit = 0;
$offset = 15;

$tt = intval(v('start'))  ;
if ($tt>0 ){
    $limit=$tt;
}
$tt = intval(v('limit'))  ;
if ($tt>0 && $tt<50){
    $offset=$tt;
}

switch ($c) {
	case 'default':
		switch ($a) {
			case 'newmap':
				$map_type = 'map';
				$mapJson = gen_new_map();   //城市村庄周边
				$code = kis_uuid();
				$cgi .= '&reload='.$code;
				save_random_map_info($mapJson,$code,array('ud3'=>0,'ud4'=>'W'.$w.',H'.$h));
                $map_html = gen_show_html($pagestartime);
				break;

            case 'settitle':
                $tt = v('reload') ;
                if (strlen($tt)==32 ){
                    $map_uuid=strtolower($tt);
                    $cgi .= '&reload='.$map_uuid;
                }
                reload_map($map_uuid);
                $map_html = gen_show_html($pagestartime);
                break;
			
            case 'dungeon':
            	$map_type = 'dungeon';
                $grids = debug_init_map($w,$h);
                $map_html_debug= '';
                $mapJson = gen_new_dungeon();   //地牢                
                if($mapJson && $mapJson['map']){
                	$code = kis_uuid();
                	$cgi .= '&reload='.$code;
                	save_random_map_info($mapJson,$code,array('ud3'=>1,'ud4'=>'W'.$w.',H'.$h));	
                }
                $map_html = gen_show_html($pagestartime,1);
                break;

			default:
                echo '#1:';
				die('403 Access Denied/Forbidden');
		}
		break;

	case 'show':
		switch ($a) {
			case 'reload':
				$tt = v('reload') ;
				if (strlen($tt)==32 ){
				    $map_uuid=strtolower($tt);
				    $cgi .= '&reload='.$map_uuid;
				}
				reload_map($map_uuid);
                $map_html = gen_show_html($pagestartime);
				break;

            case 'alllink':
                $map_html = show_all_link();
                $html_tpl='link_tpl';
                break;

            case 'map':
            	$map_type = 'map';
                $map_html = show_all_link(0);
                $html_tpl='link_tpl';
                break;	

            case 'dungeon':
            	$map_type = 'dungeon';
                $map_html = show_all_link(1);
                $html_tpl='link_tpl';
                break;

			default:
                echo '#2:';
				die('403 Access Denied/Forbidden');
		}
		break;
	
	default:
        echo '#3:';
		die('403 Access Denied/Forbidden');
}

/**


*/

if($action && $c=='show' && ($a=='map' || $a=='dungeon' || $a=='alllink')){
	echo $map_html;

}else if($a){

	// if($debugMode && $all_func_name_arr!=null) echo print_r($all_func_name_arr,true);

	if($debugMode && isset($map_html_debug)) {
		// $ret_html = debug_map_html($grids);
      	// $ret_html .='<hr color="red"/><br/><br/><br/>'.PHP_EOL.PHP_EOL.PHP_EOL;  
      	echo $map_html_debug;
	}

	$out = array(
		'ver' => 'v20141120', 
		'html_res_root' => 'html', 
		'html_res2_root' => 'http://shdic1.duapp.com/apps/sheepy_arena/html', 
		'debug_showNodeSetInfo' => debug_showNodeSetInfo(),
		'mapsize' => 'W'.$w.',H'.$h,  
		'reload_cgi' => '&c=show&a=reload'.$cgi,
		'map_html' => $map_html,
		'map_type' => $map_type==null?'alllink':$map_type,
		'time_log' => $time_log,		
		'author' => '492607291#qq.com'
	);
	
	/* Load and display map */
    if(empty($html_tpl)){
        $html_tpl='page_tpl';
    }
	$tbs = template_load($html_tpl);
	$tbs->Show();

}else{
	echo 'W'.$w.',H'.$h;
}

?>

